<script setup>
import {onMounted, ref} from "vue";
import {doGet, doPost, doPut} from "../../util/request.js";
import {showMessage} from "../../util/message.js";
import {useRoute, useRouter} from "vue-router";

// 创建新增用户对象
const user = ref({})
// 创建路由对象
const router = useRouter()
// 创建路由参数对象
const route = useRoute()

// 创建用户表单元素验证规则
const userFormRules = {
  loginAct: [
    {required: true, message: '请输入帐号', trigger: 'blur'},
    {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
  ],
  loginPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/, message: '密码由6-20位数字和字母组成', trigger: 'blur'}
  ],
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {min: 11, max: 11, message: '只支持11位的手机号码', trigger: 'blur'},
    { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']},
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱地址2', trigger: 'blur'}
  ],
  accountNoExpired: [
    {required: true, message: '请选择', trigger: 'change'},
  ],
  credentialsNoExpired: [
    {required: true, message: '请选择', trigger: 'change'},
  ],
  accountNoLocked: [
    {required: true, message: '请选择', trigger: 'change'},
  ],
  accountEnabled: [
    {required: true, message: '请选择', trigger: 'change'},
  ]

}

// 创建表单验证对象
const userRuleFormRef = ref()

// 提交表单
const submit = (formEl) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      let userId = user.value.id
      // 准备新增参数
      let params = {
        id: userId,
        loginAct: user.value.loginAct,
        loginPwd: user.value.loginPwd,
        phone: user.value.phone,
        name: user.value.name,
        email: user.value.email,
        accountNoExpired: user.value.accountNoExpired,
        credentialsNoExpired: user.value.credentialsNoExpired,
        accountNoLocked: user.value.accountNoLocked,
        accountEnabled: user.value.accountEnabled
      }
      console.log("用户新增请求参数：",params)
      if (userId) {
        // 有值：编辑用户
        doPut('/api/user',params)
            .then(resp => {
              if (resp.data.code === 200) {
                // 提示信息
                showMessage("编辑用户成功",'success')
                // 返回列表页面
                router.back()
              } else {
                // 提示信息
                showMessage("编辑用户失败，原因："+resp.data.msg,'error')
              }
            })
      } else {
        // 没有值：新增用户
        // 新增用户
        doPost('/api/user',params).then(resp => {
          if (resp.data.code === 200) {
            // 提示信息
            showMessage("新增用户成功",'sucess')
            // 返回列表页面
            router.back()
          } else {
            // 提示信息
            showMessage("新增用户失败，原因："+resp.data.msg,'error')
          }
        })
      }


    }
  })
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

// 查询用户信息
const loadUserInfo = (userId) => {
  // 查询用户信息
  doGet('/api/user/detail/info/'+userId,{}).then(resp => {
    if (resp.data.code === 200) {
      // 赋值
      user.value = resp.data.data
    } else {
      // 提示信息
      showMessage("查询用户信息失败，原因："+resp.data.msg,'error')
    }
  })
}

onMounted(()=>{
  // 获取路由参数用户标识
  let userId = route.params.userId
  // 判断用户id是否有值
  if (!userId) return
  // 查询编辑用户的信息
  loadUserInfo(userId)
})

const options = ref([
  {value: 1, label: '否'},
  {value: 0, label: '是'},
])

</script>

<template>
  <h1 v-if="user.id">用户编辑页面</h1>
  <h1 v-else>用户新增页面</h1>

  <el-form
      ref="userRuleFormRef"
      style="max-width: 600px;"
      :model="user"
      label-width="auto"
      :rules="userFormRules"
      class="demo-ruleForm">

    <el-form-item label="帐号" prop="loginAct">
      <el-input v-model="user.loginAct" />
    </el-form-item>

    <el-form-item label="登录密码" prop="loginPwd" v-if="!user.id">
      <el-input type="password" v-model="user.loginPwd" />
    </el-form-item>

    <el-form-item label="姓名" prop="name">
      <el-input v-model="user.name" />
    </el-form-item>

    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="user.phone" />
    </el-form-item>

    <el-form-item label="邮箱" prop="email">
      <el-input v-model="user.email" />
    </el-form-item>

    <el-form-item label="帐号是否过期" prop="accountNoExpired">
      <el-select v-model="user.accountNoExpired" placeholder="请选择">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="密码是否过期" prop="credentialsNoExpired">
      <el-select v-model="user.credentialsNoExpired" placeholder="请选择">
        <el-option v-for="item in options"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="帐号是否锁定" prop="accountNoLocked">
      <el-select v-model="user.accountNoLocked" placeholder="请选择">
        <el-option v-for="item in options"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="帐号是否可用" prop="accountEnabled">
      <el-select v-model="user.accountEnabled" placeholder="请选择">
        <el-option v-for="item in options"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label=" ">
      <el-button type="primary" @click="submit(userRuleFormRef)">提交</el-button>
      <el-button @click="resetForm(userRuleFormRef)">重置</el-button>
      <el-button @click="router.back()">返回</el-button>
    </el-form-item>

  </el-form>

</template>

<style scoped>

</style>